﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

namespace winS.UnityEditor.UIElement
{
    /// <summary>
    /// 开关按钮.
    /// 此按钮操作一个bool值, 并有样式反馈
    /// </summary>
    public class SwitchButton : Button
    {
        private const float defaultAnimationDuration = 0.4f;

        public static readonly Color defaultOnColor = new Color32(0, 210, 0, 255);
        public static readonly Color defaultOffColor = new Color32(210, 0, 0, 255);

        public new event Action<bool> onClick;

        public bool on { get => _on; set => SetOn(value); }

        public Color onColor { get => _onColor; set => SetOnColor(value); }
        public Color offColor { get => _offColor; set => SetOffColor(value); }

        private bool _on;

        private Color _onColor = defaultOnColor;
        private Color _offColor = defaultOffColor;

        internal SwitchButton(ElementFactory elementFactory) : base(elementFactory)
        {
            base.onClick += OnClickCallback;
        }

        protected override void InitializeStyle()
        {
            style.SetBorderLeft(1f, elementFactory.borderColor);
            style.SetBorderRight(1f, elementFactory.borderColor);
            style.SetBorderTop(1f, 2f, elementFactory.borderColor);
            style.SetBorderBottom(1f, offColor);
            style.SetBackgroundColor(normalColor);
            style.transitionDuration = new List<TimeValue>() { defaultAnimationDuration, defaultAnimationDuration };
            style.transitionProperty = new List<StylePropertyName>() { "border-bottom-color", "background-color" };
        }

        private void SetOn(bool newValue)
        {
            if (_on == newValue) return;
            _on = newValue;
            style.borderBottomColor = on ? onColor : offColor;
        }
        private void SetOnColor(Color color)
        {
            _onColor = color;
            style.borderBottomColor = on ? onColor : offColor;
        }
        private void SetOffColor(Color color)
        {
            _offColor = color;
            style.borderBottomColor = on ? onColor : offColor;
        }
        private void OnClickCallback()
        {
            style.borderBottomColor = (on = !on) ? onColor : offColor;
            onClick?.Invoke(on);
        }
    }
}
